/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bookstore.mvc.controller;

import bookstore.bean.LoginBean;
import bookstore.bean.OrderBean;
import bookstore.bean.OrderDetailsBean;
import bookstore.bean.OrderDetailsBean.OrderDetailBean;
import bookstore.bean.OrderListBean;
import bookstore.util.Utilities;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.PreparedStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

/**
 *
 * @author Caleido
 */
public class OrderController extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    private static String temporaryPath = "";

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        temporaryPath = getServletContext().getRealPath("/") + "temporary/";
        HttpSession session = request.getSession(true);
        LoginBean user = null;
        boolean auth = false;
        if (session.getAttribute("USER") != null) {
            user = (LoginBean) session.getAttribute("USER");
            if (user != null)
                auth = true;
        }
        try {
            String action = request.getParameter("action");
            if (action.equals("Orders")) {
                if (auth == true) {
                    String xmlPath = OrderController.getOrderSXmlById(user.getUsername());
                    request.setAttribute("ORDERS_XML_PATH", xmlPath);

                    
                }
                request.getRequestDispatcher("orderList.jsp").forward(request, response);
            } else if (action.equals("View")) {
                String orderId = request.getParameter("orderId");
                String xmlPath = OrderController.getOrderXmlById(orderId);
                request.setAttribute("ORDER_XML_PATH", xmlPath);
                request.getRequestDispatcher("orderDetails.jsp").forward(request, response);
            }
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    public static String getOrderXmlById(String orderId) {
        Connection con = null;
        ResultSet rs = null;
        PreparedStatement stm = null;
        String xmlPath = "";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/xml_bookstore", "root", "");
            String sql = "select a.OrderDetailId, a.Isbn, Title, a.quantity, price from books right join (select * from orderdetails where orderdetails.OrderId = ?) a on a.Isbn = books.Isbn;";
            String sql2 = "select orderId, orderTime, city, address, phone, name, username from orders o where o.OrderId = ?;";

            stm = con.prepareStatement(sql);
            stm.setString(1, orderId);
            rs = stm.executeQuery();

            OrderBean order = null;
            OrderDetailsBean oDetails = new OrderDetailsBean();
            List<OrderDetailBean> detailList = new ArrayList<OrderDetailBean>();
            OrderDetailBean detail = null;
            while (rs.next()) {
                detail = new OrderDetailBean(rs.getString("OrderDetailId"), rs.getString("Isbn"), rs.getString("Title"), rs.getInt("Quantity"), rs.getFloat("Price"));
                detailList.add(detail);
            }
            oDetails.setOrderDetail(detailList);
            stm = con.prepareStatement(sql2);
            stm.setString(1, orderId);
            rs = stm.executeQuery();
            if (rs.next()) {
                order = new OrderBean(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7), oDetails);
            }
            File file = new File(temporaryPath+orderId+".xml");
            JAXBContext ctx = JAXBContext.newInstance(order.getClass());
            Marshaller mar = ctx.createMarshaller();
            mar.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            mar.marshal(order, file);
            System.out.println(file.getAbsoluteFile());
            xmlPath = "temporary/"+orderId+".xml";
        } catch (JAXBException ex) {
            Logger.getLogger(OrderController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (stm != null) {
                    stm.close();
                }
                if (con != null) {
                    con.close();
                }
            } catch (Exception e) {
                System.out.println(e);
            }
        }
        return xmlPath;
    }

    public static String getOrderSXmlById(String username) {
        Connection con = null;
        ResultSet rs = null;
        PreparedStatement stm = null;
        String xmlPath = "";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/xml_bookstore", "root", "");
            String sql = "select OrderId, OrderTime from orders where username = ?";

            stm = con.prepareStatement(sql);
            stm.setString(1, username);
            rs = stm.executeQuery();

            OrderBean order = null;
            List<OrderBean> orders = new ArrayList<OrderBean>();
            while (rs.next()) {
                order = new OrderBean(rs.getString("OrderId"), rs.getString("OrderTime"), "", "", "", "", "", null);
                orders.add(order);
            }
            OrderListBean list = new OrderListBean(orders);
            File file = new File(temporaryPath+username+".xml");
            JAXBContext ctx = JAXBContext.newInstance(list.getClass());
            Marshaller mar = ctx.createMarshaller();
            mar.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            mar.marshal(list, file);
            System.out.println(file.getAbsoluteFile());
            xmlPath = "temporary/"+username+".xml";
        } catch (JAXBException ex) {
            Logger.getLogger(OrderController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (stm != null) {
                    stm.close();
                }
                if (con != null) {
                    con.close();
                }
            } catch (Exception e) {
                System.out.println(e);
            }
        }
        return xmlPath;
    }

    public static List<OrderBean> getOrdersByUsername(String username) {
        Connection con = null;
        ResultSet rs = null;
        PreparedStatement stm = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/xml_bookstore", "root", "");
            String sql = "select OrderId, OrderTime from orders where username = ?";

            stm = con.prepareStatement(sql);
            stm.setString(1, username);
            rs = stm.executeQuery();

            OrderBean order = null;
            List<OrderBean> orders = new ArrayList<OrderBean>();
            if (rs.next()) {
                order = new OrderBean(rs.getString("OrderId"), rs.getString("OrderTime"), "", "", "", "", "", null);
                orders.add(order);
            }
            return orders;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (stm != null) {
                    stm.close();
                }
                if (con != null) {
                    con.close();
                }
            } catch (Exception e) {
                System.out.println(e);
            }
        }
        return null;
    }
}
